<script>
	import Vue from "vue"
	
	import { homePath } from "@/utils/constant"
	import {jumpTo,getClientInfo,delay,switchTab} from "@/utils/util.js"
	import {reportDevice} from "@/api/user.js"
	import chat,{dictateTypes,connectStatus} from '@/IM/index.js'
	import { connectEnum } from "@/IM/IM.js"
	// #ifdef APP-PLUS
	import {createTable} from "@/services/mediaService.js"
	// #endif
	import {
		mapActions,
		mapMutations
	} from 'vuex'
	export default {
		globalData: {
			vipRuleMap:new Map(),
			front:false,
			chat,
			systemInfo:{},
			
		},
		onLaunch: function() {
			
			// #ifdef APP-PLUS
			createTable()
			// #endif
			console.log('App Launch')
			uni.onNetworkStatusChange(e=>{
				console.log("网络变化",e)
				uni.$emit('networkChange',e)
			})
			this.initUser().catch((e)=>{
				uni.reLaunch({
					url:'/pages/login/login'
				})
				console.error(e)
			});
			this.initSystem().catch((e)=>{
				console.error(e)
				const fn = ({isConnected})=>{
					isConnected&&this.initSystem().then(()=>{
						uni.$off('networkChange',fn)
					})
				}
				uni.$on('networkChange',fn)
			});
			// #ifdef APP-PLUS
			
			
			plus.screen.lockOrientation("portrait-primary");
			
			
			
			
			
			
			
			
			
			
			
			
			
			
			
			
			
			plus.push.addEventListener('click', (msg)=>{
				console.log("推送 click", msg);
				this.handlePush(msg.payload)
			});
			// #endif
			uni.getSystemInfo({
				success:({statusBarHeight,titleBarHeight,brand='',model='',platform='',system='',deviceId=''})=>{
					// #ifndef MP
					Vue.prototype.StatusBar = statusBarHeight;
					Vue.prototype.CustomBar = statusBarHeight + 44;
					// #endif
					// #ifdef MP-WEIXIN
					Vue.prototype.StatusBar = statusBarHeight;
					Vue.prototype.CustomBar = statusBarHeight+46 
					let custom = wx.getMenuButtonBoundingClientRect();
					Vue.prototype.Custom = custom;
					// #endif
					
					
					const systemInfo = {
						brand,
						model,
						platform,
						system,
						deviceId
					}
					this.globalData.systemInfo = systemInfo
					// #ifdef APP-PLUS
					if(platform=='ios'){
						delay(1000).then(()=>{
							getClientInfo().then(({clientid})=>{
								console.log(clientid)
								return reportDevice({pushId:clientid,brand,model,platform,system,deviceId,event:'start'})
							})
						})
					}else{
						if(plus.runtime.isAgreePrivacy()){
							delay(1000).then(()=>{
								getClientInfo().then(({clientid})=>{
									console.log(clientid)
									return reportDevice({pushId:clientid,brand,model,platform,system,deviceId,event:'start'})
								})
							})
						}
					}
					// #endif
					// #ifndef APP-PLUS
						reportDevice({brand,model,platform,system,deviceId,event:'start'})
					// #endif
				}
			})
		},
		onShow() {
			console.log('App Show')
			this.globalData.front = true
			uni.$emit('appShow')
			if(chat.token&&chat.userId){
				chat.oneHeart()
			}
		},
		onHide: function() {
			uni.$emit('appHide')
			console.log('App Hide')
			this.globalData.front = false
		},
		mounted() {
			chat.onClose(()=>{
				console.log('socket 链接已关闭')
				this.setOnline(false)
			})
			chat.onOpen(()=>{
				console.log('socket 链接已打开')
				this.setOnline(true)
			})
			chat.onMessage(({data})=>{
				console.log(data)
				this.receiveMessage(data);
			})
			
			
			
			
			chat.onOffline(({data})=>{ 
				console.log(data)
				this.receiveOffline(data)
			})
			chat.onPenetrate(({data})=>{
				console.log(data)
				
				
				// #ifdef APP-PLUS
				
				const {extras,msgType} = data
				if(!this.globalData.front&&msgType==dictateTypes.call){
					plus.push.createMessage(`[${extras.isAudio?'语音':'视频'}通话]`,{busType:'CMD',extras},{title:extras.from.userName,cover:true})
				}else{
					this.receivePenetrate(data)
				}
				// #endif
				// #ifndef APP-PLUS
				this.receivePenetrate(data)
				// #endif
			})
			chat.onRead(({data})=>{
				this.receiveRead(data)
			})
		},
		methods:{
			...mapActions('chat',['receiveMessage','receiveOffline','receivePenetrate','receiveRead']),
			...mapMutations('chat',['setOnline','setChannel']),
			...mapActions('user', ['initUser']),
			...mapActions('system',['initSystem']),
			async handlePush({busType,...payload}){
				if(busType=='CMD'){
					const extras = payload.extras
					this.setChannel({
						channelId:extras.roomId,
						userId:extras.from.userId,
						userName:extras.from.userName,
						avatar:extras.from.avatarUrl,
						isAudio:extras.isAudio
					})
					jumpTo('/pages/room/receive')
				}else if(busType=='IM'){
					this.toChat(payload.cId,payload.cType)
				}else{
					console.warn("未知的业务类型",busType)
				}
			},
			toChat(id,type){
				const pages = getCurrentPages()
				if(type==1){
					const index = pages.findIndex(({route,options})=>route=='pages/room/multi'&&id==options.id)
					return index<0?jumpTo(`/pages/room/multi?id=${id}`):uni.navigateBack({delta:pages.length-index-1});
				}
				if(type==2){
					const index = pages.findIndex(({route,options})=>route=='pages/room/single'&&id==options.id)
					return index<0?jumpTo(`/pages/room/single?id=${id}`):uni.navigateBack({delta:pages.length-index-1});
				}
				uni.reLaunch({
					url:homePath
				})
			}
		}
		
	}
</script>

<style lang="scss">
	
	/* #ifndef APP-NVUE */
	@import "uview-ui/index.scss";
	@import "./app.scss";
	/* #endif */
</style>
